<template>
  <div ref="echartRef" class="echart-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import svg from "@/assets/images/map.svg";
const emit = defineEmits(['map-click']);

const props = defineProps<{
  option: echarts.EChartsOption;
}>();

const echartRef = ref<HTMLDivElement | null>(null);
let echartInstance: echarts.ECharts | null = null;

const initChart = async () => {
  console.log("init", props.option)
  if (echartRef.value) {
    echartInstance = echarts.init(echartRef.value, 'dark');
    echartInstance.on('click', (params) => {
      console.log('clickparams',params);
      if (params.componentType === 'series') {
        console.log('clickparams-1',params);
        emit('map-click', params);
      }
    });
    echartInstance.getZr().on('click', (params) => {
      var pixelPoint = [params.offsetX, params.offsetY];
      var dataPoint = echartInstance.convertFromPixel({ geoIndex: 0 }, pixelPoint);    // 在 SVG 上点击时，坐标会被打印。
      // 这些坐标可以在 `series.data` 里使用。
      console.log('dataPoint',dataPoint);
    //  emit('map-click', params);

    });
    await fetch(svg).then(response => response.text()).then(svgText => {
      echarts.registerMap("track-map", { svg: svgText });
    });
    echartInstance.setOption(props.option);
  }
};

const resizeChart = () => {
  if (echartInstance) {
    nextTick(() => {
      echartInstance?.resize();
    });
  }
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  if (echartInstance) {
    echartInstance.dispose();
  }
  window.removeEventListener('resize', resizeChart);
});

// 监听 prop 中的 option 变化，在图表实例存在时更新配置
watch(
  () => props.option,
  (newOption) => {
    if (echartInstance) {
      console.log('refresh data', newOption)
      echartInstance.setOption(newOption);
    }
  },
  { deep: true } // 深度监听，以便捕捉到嵌套对象的变化
);
defineExpose({
  initChart
});
</script>
<style scoped>
.echart-container,
.echart-container div,
.echart-container canvas {
  width: 100%;
  height: 100%;
}
</style>
